﻿using System.IO;
using System.Text;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;

namespace System
{
    public static partial class Extention
    {
		//HttpContext.Session（实现了ISession接口）没有提供保存复杂对象的方法，然而我们可以通过序列化对象为字符串来实现这个功能
        public static void Set<T>(this Microsoft.AspNetCore.Http.ISession session, string key, T value)
        {
            session.SetString(key, JsonConvert.SerializeObject(value));
        }

        public static T Get<T>(this Microsoft.AspNetCore.Http.ISession session, string key)
        {
            var value = session.GetString(key);

            return value == null ? default(T) :
                JsonConvert.DeserializeObject<T>(value);
        }
        public static string GetStringNull(this ISession session, string key)
        {
            try
            {
                var value = session.GetString(key);
                return value;
            }
            catch
            {
                return string.Empty;
            }
        }
    }
}
